package com.iotproject.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.iotproject.msmservice.service.MsmService;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean getMsg(Map<String, Object> params, String phone) {
        if(StringUtils.isEmpty(phone)) return false;
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5t6rSyqojMmXfoDE3jf4")
                .accessKeySecret("6R7tZg6fA91RWFVs1XZJZLlXCWFnKC")
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("枫云在线教育系统")
                .templateCode("SMS_465645764")
                .phoneNumbers(phone)
                .templateParam(JSONObject.toJSONString(params)) //发送产生的验证码
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        try {
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            client.close();
        }
    }
}
